﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;

namespace APIIT_BPEL_Server.Business_Layer
{
    public class BPEL_Process
    {
        public string doRequest(string url, string xpaths, string parameters, string cookieString, string type)
        {
            string returnValue = "";
            bool status = true;          
            string[] resDescription;
            string[] finalResultDescription;
            string htmlSourcePlusCookies = "";

            string[] results = Regex.Split(xpaths, "==="); 

            APIIT_BPEL_Server.Http_Layer.Request_Dispatcher dispatcher = new APIIT_BPEL_Server.Http_Layer.Request_Dispatcher();

            if (type == "POST")
            {
                htmlSourcePlusCookies = dispatcher.doPost(url, parameters, cookieString);
            }
            else if (type == "GET")
            {
                htmlSourcePlusCookies = dispatcher.doGet(url, parameters, cookieString);
            }

            string[] html_cookies = Regex.Split(htmlSourcePlusCookies, "===cookie===");

            string htmlSource = html_cookies[0];

            string cookiesForReturn = html_cookies[1];

            string tempReult = "";
            APIIT_BPEL_Server.Utility.Html_Parser htmlParser = new APIIT_BPEL_Server.Utility.Html_Parser();
            for (int i = 0; i < results.Length && results[i].Trim() != ""; i++)
            { 
                resDescription = Regex.Split(results[i], ":");
                finalResultDescription = Regex.Split(resDescription[1], "---");
                returnValue = returnValue + resDescription[0];
                tempReult = htmlParser.findNode(htmlSource, finalResultDescription[0], finalResultDescription[1]);
                if (tempReult != null)
                {
                    returnValue = returnValue + "===" + tempReult;
                }
                else
                {
                    status = false;
                    returnValue = returnValue + "===" + "";
                }
                if (i < results.Length - 1)
                {
                    returnValue = returnValue + "---";
                }
            }
            returnValue = returnValue + "-=-=-" + cookiesForReturn;
            if (status)
            {
                returnValue = returnValue + "-=-=-" + "SUCCESS";
            }
            else
            {
                returnValue = returnValue + "-=-=-" + "ERROR";
            }
            return returnValue;
        }

    }
}